package com.revenant.driver.base;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.apkfuns.logutils.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hdgq.locationlib.LocationOpenApi;
import com.hdgq.locationlib.listener.OnResultListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.revenant.driver.BuildConfig;
import com.revenant.driver.R;
import com.revenant.driver.adapter.AlertInfoListAdapter;
import com.revenant.driver.bean.UpdateBean;
import com.revenant.driver.ui.XieYiActivity;
import com.revenant.driver.ui.activity.DriverMainActivity;
import com.revenant.driver.utils.Constants;
import com.revenant.driver.utils.GsonUtil;
import com.revenant.driver.utils.PermissionConstants;
import com.revenant.driver.utils.PermissionUtils;
import com.revenant.driver.utils.SPUtils;
import com.revenant.driver.utils.apkUpdate.VersionUtils;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import constant.UiType;
import listener.OnBtnClickListener;
import model.UiConfig;
import model.UpdateConfig;
import update.UpdateAppUtils;

public class SplashActivity extends BaseActivity {
    @BindView(R.id.show_image)
    ImageView showImage;
    private String apkUrl = "";
    private String updateTitle = "";
    private String updateContent = "";
    String appId = "com.revenant.driver";
    String appSecurity = "e59fba3aa687732f6d3d83f5f2c33182b3f8a75d2c693f62c132e042ada7241176a90b3a9c0f225671bd4671367909b3";
    String enterpriseSenderCode = "2114264";
    String environment = "debug";
    private Context context;
    private int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;
    private PopupWindow popstart;
    private boolean isSelect = false;

    @Override
    public int getContentViewResId() {
        return R.layout.activity_splash;
    }

    @Override
    public void initView() {
        context = this;

        alertDialog();

//        App.flag = 0;
//        RestartUtils.getInstance().setAppStatus(STATUS_NORMAL);
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        String rid = JPushInterface.getRegistrationID(getApplicationContext());
        com.blankj.utilcode.util.LogUtils.d("AAAAAAAAAAAAAAAAAAAAAAA"+rid);
        SPUtils.setUpdateNum(getApplication(), 1);
        SPUtils.setHeaderToken(getApplication(), 1);
//        SPUtils.setPushCode(getApplication(), 0);
        if (SPUtils.getJpRidToken(getApplicationContext()).isEmpty()) {
            if (!rid.isEmpty()) {
                SPUtils.setJpRidToken(getApplicationContext(), rid);
            }
        }

        initLoation();
//        updateApks();
    }

    private void initLoation() {
        LocationOpenApi.init(
                context,
                appId,
                appSecurity,
                enterpriseSenderCode,
                environment,
                new OnResultListener() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onFailure(String s, String s1) {

                        LogUtils.d("SplaActivity" + "code:" + s + "msg:" + s1);

                    }
                }
        );
    }

    @Override
    protected boolean isshowtitlebar() {
        return false;
    }

    @Override
    public void initData() {
        checkPermission();
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkPermission();
    }

    /**
     * 请求权限
     */
    public void checkPermission() {

//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
//                != PackageManager.PERMISSION_GRANTED) {
//            //申请WRITE_EXTERNAL_STORAGE权限
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
//                    WRITE_COARSE_LOCATION_REQUEST_CODE);//自定义的code
//        }

        boolean enabled = NotificationManagerCompat.from(this).areNotificationsEnabled();
        if (enabled) {
            PermissionUtils.permission(
                    PermissionConstants.STORAGE,
                    PermissionConstants.PHONE,
                    PermissionConstants.LOCATION,
                    PermissionConstants.MICROPHONE,
                    PermissionConstants.CAMERA)
                    .rationale(new PermissionUtils.OnRationaleListener() {
                        @Override
                        public void rationale(ShouldRequest shouldRequest) {
                            shouldRequest.again(true);
                        }
                    })
                    .callback(new PermissionUtils.FullCallback() {
                        @Override
                        public void onGranted(List<String> permissionsGranted) {


                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {


                                    boolean testUpdate = false;
                                    if (testUpdate) {
                                        updateApks();
                                    } else {
                                        startActivity(DriverMainActivity.class);
                                        finish();
                                    }
                                }
                            }, 1000);
                        }

                        @Override
                        public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                            if (!permissionsDeniedForever.isEmpty()) {
                                showMissingPermissionDialog("必须");
                                return;
                            }
                            checkPermission();
                        }
                    })
                    .request();
        } else {
            checkNotification();
        }


    }

    public void showMissingPermissionDialog(String s) {
        AlertDialog.Builder builder = new AlertDialog.Builder(SplashActivity.this);
        final AlertDialog alertDialog = builder.create();
        builder.setMessage("当前应用缺少-" + s + "-权限。\n\n请点击\"设置\"-\"权限\"-打开所需权限。\n\n最后点击两次后退按钮，即可返回。");
        // 拒绝, 退出应用
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
                finish();
            }
        });
        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                alertDialog.dismiss();
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + BuildConfig.APPLICATION_ID));
                startActivity(intent);
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    private void updateApks() {
        OkGo.<String>get(Constants.Update_Apk_0825)
                .params("appVersion", VersionUtils.getVersionCode())
                .params("platform", "0")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateBean updateBean = GsonUtil.parseJsonWithGson(response.body(), UpdateBean.class);
                        if (updateBean.getData() != null) {
                            Integer versioncode = Integer.valueOf(updateBean.getData().getVersion());
                            if (versioncode > VersionUtils.getVersionCode()) {
                                updateTitle = updateBean.getData().getTitle();
                                updateContent = updateBean.getData().getContent();
                                apkUrl = updateBean.getData().getUrl();
                                boolean isAuto = updateBean.getData().isIsAuto();

                                if (updateBean.getData().getAutoVersion()!=null){
                                    Integer integer = Integer.valueOf(updateBean.getData().getAutoVersion());
                                    if (VersionUtils.getVersionCode()<integer){
                                        isAuto=true;
                                    }
                                }


                                String name = "driver";
                                File filePictures = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
                                String absolutePath1 = filePictures.getAbsolutePath();
                                String androidQpath = absolutePath1 + "/" + name;

                                UpdateConfig updateConfig = new UpdateConfig();
                                updateConfig.setCheckWifi(false);
                                updateConfig.setNeedCheckMd5(false);
                                updateConfig.setShowNotification(true);
                                updateConfig.setShowDownloadingToast(true);
                                updateConfig.setAlwaysShowDownLoadDialog(true);
                                updateConfig.setApkSaveName(name);
                                updateConfig.setApkSavePath(androidQpath);
                                updateConfig.setNotifyImgRes(R.mipmap.icon);
                                updateConfig.setForce(isAuto);
                                final UiConfig uiConfig = new UiConfig();
                                uiConfig.setUiType(UiType.PLENTIFUL);
                                uiConfig.setCancelBtnText("下次再说");
                                uiConfig.setUpdateBtnText("立即升级");

                                UpdateAppUtils
                                        .getInstance()
                                        .apkUrl(apkUrl)
                                        .updateTitle(updateTitle)
                                        .updateContent(updateContent)
                                        .uiConfig(uiConfig)
                                        .updateConfig(updateConfig)
                                        .setUpdateBtnClickListener(new OnBtnClickListener() {
                                            @Override
                                            public boolean onClick() {
                                                return false;
                                            }
                                        })
                                        .setCancelBtnClickListener(new OnBtnClickListener() {
                                            @Override
                                            public boolean onClick() {
                                                finish();
                                                startActivity(DriverMainActivity.class);
                                                return false;

                                            }
                                        })
                                        .update();
                            } else {
                                startActivity(DriverMainActivity.class);
                                finish();
                            }

                        } else {
                            startActivity(DriverMainActivity.class);
                            finish();
                        }
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        String msgerror = response.getException().getMessage();
                        showLongToast(msgerror);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    private void checkNotification() {

        new QMUIDialog.MessageDialogBuilder(this).
                setTitle("请开启通知").
                addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                        showNotication();
                    }
                }).create(mCurrentDialogStyle).show();


    }

    private void showNotication() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            Intent intent = new Intent();
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", getPackageName());
            intent.putExtra("app_uid", getApplicationInfo().uid);
            startActivity(intent);
        } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        } else {
            Intent localIntent = new Intent();
            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
            startActivity(localIntent);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }



    private void alertDialog() {
        View contentView = View.inflate(this, R.layout.alert_dialog_show, null);
        Button imageclose = (Button) contentView.findViewById(R.id.kaiqi);

        popstart = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,
                true
        );

        imageclose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popstart.dismiss();
                showNotication();
            }
        });
        popstart.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        // 设置PopupWindow是否能响应外部点击事件
        popstart.setOutsideTouchable(false);
        // 设置PopupWindow是否能响应点击事件
        popstart.setTouchable(true);
        popstart.setContentView(contentView);

        popstart.setAnimationStyle(R.style.Popupwindow);

        popstart.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkenBackground(1f);
            }
        });


    }

    private void darkenBackground(Float alpha) {
        if (alpha < 0 || alpha > 1) {
            return;
        }
        WindowManager.LayoutParams windowLP = getWindow().getAttributes();
        windowLP.alpha = alpha;
        if (alpha == 1) {
            //不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        } else {
            //此行代码主要是解决在华为手机上半透明效果无效的bug
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        }
        getWindow().setAttributes(windowLP);

    }
}
